package com.sz.biz.common.customer.service.impl;

import com.sz.biz.common.utils.PassWordCreate;
import com.sz.biz.common.constants.ErrorCodes;
import com.sz.biz.common.constants.ModuleNames;
import com.sz.biz.common.customer.entity.CusCustomer;
import com.sz.biz.common.customer.entity.CusUser;
import com.sz.biz.common.customer.service.CustomerService;
import com.sz.biz.common.customer.service.CustomerUserService;
import com.sz.biz.common.customer.dto.CusUserIdNameDto;
import com.sz.biz.common.customer.dto.CusUserSimpleDto;
import com.sz.common.base.constants.TemplateConstants;
import com.sz.common.base.constants.UserActions;
import com.sz.common.base.dao.ParamData;
import com.sz.common.base.dto.CodeNameDto;
import com.sz.common.base.dto.QResultDto;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.service.AbstractService;
import com.sz.common.base.utils.CheckDataUtils;
import com.sz.common.base.utils.CredentialUtils;
import com.sz.common.base.utils.JsonUtils;
import com.sz.common.base.utils.StringUtils;
import com.sz.common.core.service.PrincipalLogUtils;
import com.sz.common.core.service.PrincipalUtils;
import com.sz.common.core.system.dto.FileInfoDto;
import com.sz.common.core.system.service.SysFileGroupService;
import com.sz.common.core.system.service.SysMailService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * Created by xutao on 17/3/28.
 */
@Service("CustomerUserInfoService")
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class CustomerUserServiceImpl extends AbstractService implements CustomerUserService {

    private static final String STRING = "_";
    private static final String UNDER_LINE = "-";
    @Autowired
    private SysMailService mailService;

    @Autowired
    CustomerService customerService;

    @Autowired
    SysFileGroupService fileGroupService;

    @Override
    protected String getMapperNamespace() {
        return "CusUserMapper";
    }

    @Override
    public int save(CusUser entry) {
        String tempPswd = null;
        if (entry != null) {
            if (entry.getPassword() == null || "".equalsIgnoreCase(entry.getPassword())) {
                PassWordCreate pwc = new PassWordCreate();
                String pswd = pwc.createPassWord(6);
                entry.setPassword(pswd);
            }
            checkDataValid(entry);
            checkUserExist(entry);
            String credentialSalt = CredentialUtils.generateSalt();
            entry.setCredentialSalt(credentialSalt);
            tempPswd = entry.getPassword();
            String encryptionPswd = encryptionProc(entry.getPassword(), credentialSalt);
            entry.setPassword(encryptionPswd);
            entry.setNeedResetPwd(true);
            dao.save(getSqlName("insertSelective"), entry);
            Map<String, Object> emailBodyMap = new HashMap<>();
            emailBodyMap.put("username", entry.getUserName());
            emailBodyMap.put("password", tempPswd);
            String emailBody = JsonUtils.toJSONString(emailBodyMap);
            // 发邮件
            mailService.createMail("sys.logistics.master@hna.com", new String[]{entry.getEmail()},
                    "客户账号初始密码通知",
                    emailBody, TemplateConstants.INIT_PASSWORD_CUSTOMER);

            Map<String, Object> dataBackup = new HashMap<>();
            dataBackup.put("ADD_CUSTOMER_USER", entry);
            PrincipalLogUtils.addOperationLog(ModuleNames.CUS, ModuleNames.CUS_CUSTOMER, UserActions.ADD, "新建客户账号", dataBackup);
        }
        return 0;
    }

    @Override
    public void batchsave(List<CusUser> list) {

        if (list != null && list.size() > 0) {

            for (int i = 0; i < list.size(); i++) {

                checkDataValid(list.get(i));

                checkUserExist(list.get(i));

                String credentialSalt = CredentialUtils.generateSalt();

                list.get(i).setCredentialSalt(credentialSalt);

                String encryptionPswd = encryptionProc(list.get(i).getPassword(), credentialSalt);

                list.get(i).setPassword(encryptionPswd);
            }

            dao.batchInsert(getSqlName("insertSelective"), list);
        }

        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("ADD_CUSTOMER_USER", list);
        PrincipalLogUtils.addOperationLog(ModuleNames.CUS, ModuleNames.CUS_CUSTOMER, UserActions.ADD, "批量新建客户账号", dataBackup);
    }

    @Override
    public void batchDelete(List<Integer> ids) {

        if (ids != null && ids.size() > 0) {

            for (int i = 0; i < ids.size(); i++) {

                CusUser cusUser = (CusUser) dao.findForObject(getSqlName("findById"), ids.get(i));

                if (cusUser.getIsSystem()) {

                    throw Exceptions.bizException(ErrorCodes.ERROR_CUSTOMER_NOT_DELETED_CAUSEDBY_ADMIN);
                }

            }

            dao.update(getSqlName("logicDeleteByIds"), ids);
        }

        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("DELETE_CUSTOMER_USER", ids);
        PrincipalLogUtils.addOperationLog(ModuleNames.CUS, ModuleNames.CUS_CUSTOMER, UserActions.DELETE, "批量删除客户账号", dataBackup);
    }

    @Override
    public void lockCustomer(List<Integer> ids) {

        if (ids != null && ids.size() > 0) {

            List<Integer> mainAccountIds = new ArrayList<Integer>();

            for (int i = 0; i < ids.size(); i++) {

                CusUser cusUserInfo = (CusUser) dao.findForObject(getSqlName("selectByPrimaryKey"), ids.get(i));

                if (cusUserInfo.getIsSystem()) {

                    mainAccountIds.add(cusUserInfo.getRefCustomerId());
                }
            }

            if (mainAccountIds != null && mainAccountIds.size() > 0) {

                customerService.lockCustomer(mainAccountIds);
            }

            dao.update(getSqlName("lockCustomer"), ids);
        }

        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("LOCK_CUSTOMER_USER", ids);
        PrincipalLogUtils.addOperationLog(ModuleNames.CUS, ModuleNames.CUS_CUSTOMER, UserActions.LOCK, "锁定客户账号", dataBackup);
    }

    @Override
    public void unlockCustomer(List<Integer> ids) {
        if (ids != null && ids.size() > 0) {
            List<Integer> mainAccountIds = new ArrayList<Integer>();
            for (int i = 0; i < ids.size(); i++) {
                CusUser cusUserInfo = (CusUser) dao.findForObject(getSqlName("selectByPrimaryKey"), ids.get(i));
                if (cusUserInfo.getIsSystem()) {
                    CusCustomer cusCustomer = customerService.findSimpleById(cusUserInfo.getRefCustomerId());
                    if (cusCustomer != null) {
                        mainAccountIds.add(cusUserInfo.getRefCustomerId());
                        if (cusCustomer.getAuthStatus() != null && cusCustomer.getAuthStatus() == 1) {
                            customerService.setCustomerAuthStatus(cusUserInfo.getRefCustomerId(), 2);
                        }
                    }
                }
            }
            if (mainAccountIds != null && mainAccountIds.size() > 0) {
                customerService.unlockCustomer(mainAccountIds);
            }
            dao.update(getSqlName("unlockCustomer"), ids);
        }
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("UNLOCK_CUSTOMER_USER", ids);
        PrincipalLogUtils.addOperationLog(ModuleNames.CUS, ModuleNames.CUS_CUSTOMER, UserActions.UNLOCK, "解锁客户账号", dataBackup);
    }

    @Override
    public void updateCustomer(List<CusUser> list) {

        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                checkDataValid(list.get(i));
                checkUserExist(list.get(i));
                CusUser cusUserInfo = (CusUser) dao.findForObject(getSqlName("selectByPrimaryKey"), list.get(i).getId());
                if (list.get(i).getPassword() != null && "".equalsIgnoreCase(list.get(i).getPassword())) {
                    String encryptionPswd = encryptionProc(list.get(i).getPassword(), cusUserInfo.getCredentialSalt());
                    list.get(i).setPassword(encryptionPswd);
                }
            }

            dao.batchUpdate(getSqlName("updateByIds"), list);
        }

        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("UPDATE_CUSTOMER_USER", list);
        PrincipalLogUtils.addOperationLog(ModuleNames.CUS, ModuleNames.CUS_CUSTOMER, UserActions.UPDATE, "更新客户账号", dataBackup);
    }

    @Override
    public QResultDto findCustomerList(String q, int pageIndex, int pageSize, String sortName, boolean isAsc, String language, int refCustomerId) {

        ParamData pd = this.convertQueryParams(new QueryParams(pageSize, pageIndex, q, sortName, isAsc, language).put("refCustomerId", refCustomerId));

        List<CusUser> cusUserInfoList = dao.findForList(getSqlName("findByParamListPage"), pd, CusUser.class);

        QResultDto qResultDto = new QResultDto();
        qResultDto.setData(cusUserInfoList);
        qResultDto.setPagination(pd.getPagination());

        return qResultDto;
    }

    @Override
    public void changeCustomerPassword(Integer id, String oldPassword, String newPassword) {

        CusUser queryRes = (CusUser) dao.findForObject(getSqlName("selectByPrimaryKey"), id);

        if (queryRes == null) {

            throw Exceptions.bizException(ErrorCodes.ERROR_MODEL_NOT_FOUND, id);
        }

        String oldHash = new Md5Hash(oldPassword, queryRes.getCredentialSalt()).toString();

        if (!oldHash.equalsIgnoreCase(queryRes.getPassword())) {
            throw Exceptions.bizException(ErrorCodes.ERROR_CUSTOMER_USER_OLD_PASS_NOT_MATCH);
        }

        if (!CheckDataUtils.checkPasswordAnySpecCharacter(newPassword)) {
            throw Exceptions.bizException(ErrorCodes.ERROR_CUSTOMER_USER_PASSWORD_FORMAT_ERROR);
        }

        String updatePassword = new Md5Hash(newPassword, queryRes.getCredentialSalt()).toString().toUpperCase();

        CusUser cusUser = new CusUser();

        cusUser.setId(queryRes.getId());
        cusUser.setPassword(updatePassword);


        dao.update(getSqlName("updatePasswordById"), cusUser);

        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("CHANGE_CUSTOMER_USER_PASSWORD", queryRes);
        PrincipalLogUtils.addOperationLog(ModuleNames.CUS, ModuleNames.CUS_CUSTOMER, UserActions.UPDATE, "更改客户账号密码", dataBackup);

    }

    private String encryptionProc(String pswd, String credentialSalt) {
        return new Md5Hash(pswd, credentialSalt).toString();
    }

    private void checkDataValid(CusUser cusUser) {

        if (StringUtils.isEmpty(cusUser.getUserName())) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "username");
        }

        if (StringUtils.isEmpty(cusUser.getFullName())) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "fullname");
        }

        if (StringUtils.isEmpty(cusUser.getMobilePhone())) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "mobilephone");
        }

        if (StringUtils.isEmpty(cusUser.getEmail())) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "email");
        }

        if (cusUser.getRefCustomerId() == 0) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "customerID");
        }

    }

    private void checkUserExist(CusUser cusUser) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", cusUser.getId());
        map.put("email", cusUser.getEmail());
        CusUser userExist = (CusUser) dao.findForObject(getSqlName("findByEmail"), map);
        if (userExist != null) {
            throw Exceptions.bizException(ErrorCodes.ERROR_CUSTOMER_USER_EMAIL_EXIST);
        }

        map = new HashMap<>();
        map.put("id", cusUser.getId());
        map.put("userName", cusUser.getUserName());
        userExist = (CusUser) dao.findForObject(getSqlName("findByUserName"), map);
        if (userExist != null) {
            throw Exceptions.bizException(ErrorCodes.ERROR_MODEL_NAME_EXIST, cusUser.getUserName());
        }
        if (this.checkMobilePhoneExist(cusUser.getId(), cusUser.getMobilePhone())) { // 电话唯一校验
            throw Exceptions.bizException(ErrorCodes.ERROR_CUSTOMER_USER_PHONE_EXIST, cusUser.getMobilePhone());
        }
    }

    @Override
    public void customerEmailCheck(int userId, String email) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", userId);
        map.put("email", email);
        CusUser userExist = (CusUser) dao.findForObject(getSqlName("findByEmail"), map);
        if (userExist != null) {
            throw Exceptions.bizException(ErrorCodes.ERROR_CUSTOMER_USER_EMAIL_EXIST);
        }
    }

    @Override
    public boolean customerEmailExist(int userId, String email) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", userId);
        map.put("email", email);
        CusUser userExist = (CusUser) dao.findForObject(getSqlName("findByEmail"), map);
        return userExist != null;
    }

    @Override
    public void customerUserNameCheck(int userId, String userName) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", userId);
        map.put("userName", userName);
        CusUser userExist = (CusUser) dao.findForObject(getSqlName("findByUserName"), map);
        if (userExist != null) {
            throw Exceptions.bizException(ErrorCodes.ERROR_MODEL_USERNAME_EXIST);
        }
    }

    @Override
    public QResultDto getUserNameList(String q, int pageIndex, int pageSize, String sortName,
                                      boolean isAsc, String language, Integer userType) {

        if (userType == null || userType < 1) {
            userType = 1;
        }

        ParamData pd = this.convertQueryParams(new QueryParams(pageSize, pageIndex, q,
                sortName, isAsc, language).put("userType", userType));

        List<CusUser> cusUserInfoList = dao.findForList(getSqlName("getUserNameListPage"), pd, CusUser.class);


        QResultDto qResultDto = new QResultDto();
        qResultDto.setData(cusUserInfoList);
        qResultDto.setPagination(pd.getPagination());

        return qResultDto;
    }

    @Override
    public QResultDto getFullNameList(String q, int pageIndex, int pageSize, String sortName, boolean isAsc, String language) {
        ParamData pd = this.convertQueryParams(new QueryParams(pageSize, pageIndex, q, sortName, isAsc, language));

        List<CusUser> cusUserInfoList = dao.findForList(getSqlName("getFullNameListPage"), pd, CusUser.class);


        QResultDto qResultDto = new QResultDto();
        qResultDto.setData(cusUserInfoList);
        qResultDto.setPagination(pd.getPagination());

        return qResultDto;
    }

    @Override
    public QResultDto getPrimaryAccountListPage(String q, int pageIndex, int pageSize, String sortName, boolean isAsc, String language) {
        ParamData pd = this.convertQueryParams(new QueryParams(pageSize, pageIndex, q, sortName, isAsc, language));

        List<CusUser> cusUserInfoList = dao.findForList(getSqlName("getPrimaryAccountListPage"), pd, CusUser.class);


        QResultDto qResultDto = new QResultDto();
        qResultDto.setData(cusUserInfoList);
        qResultDto.setPagination(pd.getPagination());

        return qResultDto;
    }

    @Override
    public QResultDto getTradingCurencyByUserId(int id) {

        Map<String, Object> paramMap = new HashedMap();

        paramMap.put("id", id);
        paramMap.put("language", PrincipalUtils.getLocalLanguage());

        CodeNameDto codeNameDto = (CodeNameDto) dao.findForObject(getSqlName("getTradingCurencyByUserId"), paramMap);

        QResultDto qResultDto = new QResultDto();

        qResultDto.setData(codeNameDto);

        return qResultDto;
    }

    @Override
    public boolean checkMobilePhoneExist(Integer userId, String mobilePhone) {
        if (STRING.equals(mobilePhone) || UNDER_LINE.equals(mobilePhone)) {
            return false;
        }
        Map<String, Object> map = new HashMap<>();
        if (userId != null && userId > 0) {
            map.put("id", userId);
        }
        map.put("mobilePhone", mobilePhone);
        boolean isExist = false;
        List<CusUser> cusUserList = dao.findForList(getSqlName("findByMobilephone"), map, CusUser.class);
        if (cusUserList != null && cusUserList.size() > 0) {
            isExist = true;
        }
        return isExist;
    }

    @Override
    public boolean telNoExist(String mobilePhone) {

        boolean isExist = false;

        List<CusUser> cusUserList = dao.findForList(getSqlName("telNoExist"), mobilePhone, CusUser.class);

        if (cusUserList != null && cusUserList.size() > 0) {

            isExist = true;
        }

        return isExist;
    }

    @Override
    public CusUser selectByTelNo(String mobilePhone) {

        CusUser cusUser = null;

        List<CusUser> cusUserList = dao.findForList(getSqlName("selectByTelNo"), mobilePhone, CusUser.class);

        if (cusUserList != null && cusUserList.size() > 0) {

            cusUser = cusUserList.get(0);
        }

        return cusUser;
    }

    @Override
    public void forgetPasswordForReset(Integer id, String newPassword, String confirmPassword) {
        CusUser queryRes = (CusUser) dao.findForObject(getSqlName("selectByPrimaryKey"), id);

        if (queryRes == null) {

            throw Exceptions.bizException(ErrorCodes.ERROR_MODEL_NOT_FOUND, id);
        }

        if (!newPassword.equals(confirmPassword)) {

            throw Exceptions.bizException(ErrorCodes.ERROR_CUSTOMER_USER_PASSWORD_NOT_MATCH);
        }

        if (!CheckDataUtils.checkPasswordAnySpecCharacter(newPassword)) {
            throw Exceptions.bizException(ErrorCodes.ERROR_CUSTOMER_USER_PASSWORD_FORMAT_ERROR);
        }

        queryRes.setPassword(
                new Md5Hash(newPassword, queryRes.getCredentialSalt()).toString().toUpperCase());
        queryRes.setNeedResetPwd(false);

        dao.update(getSqlName("updatePasswordById"), queryRes);

    }

    @Override
    public Boolean userNameIsExist(Integer userId, String userName) {

        Boolean isExist = false;

        Map<String, Object> map = new HashMap<>();
        map.put("id", userId);
        map.put("userName", userName);

        CusUser userExist = (CusUser) dao.findForObject(getSqlName("findByUserName"), map);

        if (userExist != null) {

            isExist = true;
        }

        return isExist;
    }

    @Override
    public QResultDto findSimpleCustomerList(String q, int pageIndex, int pageSize, String sortName, boolean isAsc, String language, int refCustomerId) {

        ParamData pd = this.convertQueryParams(new QueryParams(pageSize, pageIndex, q, sortName, isAsc, language).put("refCustomerId", refCustomerId));

        List<CusUser> cusUserInfoList = dao.findForList(getSqlName("findSimpleCustomerListPage"), pd, CusUser.class);

        List<CusUserSimpleDto> cusUserSimpleDtoList = new ArrayList<CusUserSimpleDto>();

        if (cusUserInfoList != null && cusUserInfoList.size() > 0) {

            for (int i = 0; i < cusUserInfoList.size(); i++) {

                CusUserSimpleDto cusUserSimpleDto = new CusUserSimpleDto();

                BeanUtils.copyProperties(cusUserInfoList.get(i), cusUserSimpleDto);

                if (cusUserInfoList.get(i).getUserAvatar() != null && !"".equals(cusUserInfoList.get(i).getUserAvatar())) {

                    List<FileInfoDto> attachments = fileGroupService.getFileDtosByGroupId(cusUserInfoList.get(i).getUserAvatar());

                    if (attachments != null && attachments.size() > 0) {

                        cusUserSimpleDto.setUserAvatar(attachments.get(0).getPath());
                    }

                }

                cusUserSimpleDtoList.add(cusUserSimpleDto);
            }
        }

        QResultDto qResultDto = new QResultDto();
        qResultDto.setData(cusUserSimpleDtoList);
        qResultDto.setPagination(pd.getPagination());

        return qResultDto;
    }

    @Override
    public QResultDto findSubAccountByLoginId(Integer refCustomerId, String q,
                                              int pageIndex, int pageSize) {

        ParamData pd = this.convertQueryParams(new QueryParams(pageSize, pageIndex, q, null,
                false, null).put("refCustomerId", refCustomerId));

        List<CusUserIdNameDto> cusUserIdNameDtoList = dao.findForList(getSqlName("findSubAccountByLoginIdListPage"),
                pd, CusUserIdNameDto.class);

        QResultDto qResultDto = new QResultDto();
        qResultDto.setData(cusUserIdNameDtoList);
        qResultDto.setPagination(pd.getPagination());

        return qResultDto;
    }

    @Override
    public void updateEmailById(Integer id, String email) {

        Map<String, Object> map = new HashedMap();

        map.put("id", id);
        map.put("email", email);

        dao.update(getSqlName("updateEmailById"), map);
    }

    @Override
    public void resetUsersPasswd(List<Integer> userIds) {
        for (Integer userId : userIds) {
            CusUser cusUser = (CusUser) dao.findForObject(getSqlName("selectByPrimaryKey"), userId);
            if (cusUser != null) {
                String randomPassword = CredentialUtils.randomPassword();
                cusUser.setPassword(new Md5Hash(randomPassword, cusUser.getCredentialSalt()).toString());
                cusUser.setNeedResetPwd(true);
                dao.update(getSqlName("updatePasswordById"), cusUser);

                Map<String, Object> emailBodyMap = new HashMap<>();
                emailBodyMap.put("username", cusUser.getUserName());
                emailBodyMap.put("password", randomPassword);
                String emailBody = JsonUtils.toJSONString(emailBodyMap);
                // 发邮件
                mailService.createMail("sys.logistics.master@hna.com", new String[]{cusUser.getEmail()},
                        "客户账号密码重置通知",
                        emailBody, TemplateConstants.RESET_PASSOWRD_CUSTOMER);
            }
        }

        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("UPDATE_CUSTOMER_USER", userIds);
        PrincipalLogUtils.addOperationLog(ModuleNames.CUS, ModuleNames.CUS_CUSTOMER, UserActions.UPDATE, "重置客户账号密码", dataBackup);

    }


    @Override
    public List<CusUser> findByCustomerId(Integer refCustomerId) {

        List<CusUser> cusUserList = dao.findForList(getSqlName("findByCustomerId"), refCustomerId, CusUser.class);

        return cusUserList;
    }

    /**
     * 凭借customerid查账子账户信息-包括已经删除的子帐号
     */
    @Override
    public List<CusUser> findByCustomerIdIncludeDeleted(Integer refCustomerId) {
        List<CusUser> cusUserList = dao.findForList(getSqlName("findByCustomerIdIncludeDeleted"), refCustomerId, CusUser.class);

        return cusUserList;
    }

    @Override
    public CusUser findById(Integer id) {

        CusUser cusUser = (CusUser) dao.findForObject(getSqlName("selectByPrimaryKey"), id);

        return cusUser;
    }

    @Override
    public List<CusUser> findByIds(List<Integer> ids) {
        List<CusUser> cusUserList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(ids)) {
            ParamData pd = new ParamData();
            pd.put("ids", ids);
            cusUserList = dao.findForList(getSqlName("findByIds"), pd, CusUser.class);
        }

        return cusUserList;
    }

    @Override
    public List<CusUser> findShortByIds(List<Integer> ids) {
        List<CusUser> cusUserList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(ids)) {
            ParamData pd = new ParamData();
            pd.put("ids", ids);
            cusUserList = dao.findForList(getSqlName("findShortByIds"), pd, CusUser.class);
        }

        return cusUserList;
    }

    @Override
    public CusUser findShortById(Integer id) {
        CusUser cusUser = null;
        if (!ObjectUtils.isEmpty(id)) {
            List<CusUser> cusUserList = this.findShortByIds(Arrays.asList(id));
            if (!CollectionUtils.isEmpty(cusUserList)) {
                cusUser = cusUserList.get(0);
            }
        }
        return cusUser;
    }

    /**
     * @param accountName
     * @return
     */
    @Override
    public CusUser findByAccountName(String accountName) {
        CusUser cusUser = (CusUser) dao.findForObject(getSqlName("findByCustomerAccount"), accountName);
        return cusUser;
    }

    @Override
    public QResultDto getLinkedUserNameList(String q, int pageIndex, int pageSize, String sortName,
                                            boolean isAsc, String language, Integer userType, Integer refCustomerId) {

        if (userType == null || userType < 1) {

            userType = 1;
        }

        QueryParams queryParams = new QueryParams(pageSize, pageIndex, q, sortName, isAsc, language);

        queryParams.put("userType", userType);
        queryParams.put("refCustomerId", refCustomerId);

        ParamData pd = this.convertQueryParams(queryParams);

        List<CusUser> cusUserInfoList = dao.findForList(getSqlName("getLinkedUserNameListPage"), pd, CusUser.class);


        QResultDto qResultDto = new QResultDto();
        qResultDto.setData(cusUserInfoList);
        qResultDto.setPagination(pd.getPagination());

        return qResultDto;
    }

    @Override
    public Boolean checkMainAccountLockedStatus(String userName) {

        Boolean LockedStatus = true;

        CusUser cusUser = findByAccountName(userName);

        if (cusUser != null) {

            ParamData pd = new ParamData();
            pd.put("refCustomerId", cusUser.getRefCustomerId());

            List<CusUser> systemUserList = dao.findForList(getSqlName("findSystemUserByRefCusId"), pd, CusUser.class);

            if (com.sz.common.base.utils.CollectionUtils.isEmpty(systemUserList)) {
                logger.error("=============主账号未找到=============");
                throw new UnknownAccountException("主账号未找到");//没找到帐号
            }


            if (systemUserList != null && systemUserList.size() > 0) {

                LockedStatus = systemUserList.get(0).getIsLocked();
            }

        }

        return LockedStatus;
    }

    @Override
    public boolean isUserValid(int cusUserId) {
        CusUser cusUser = (CusUser) dao.findForObject(getSqlName("findById"), cusUserId);
        if (cusUser == null || cusUser.getIsDeleted() || cusUser.getIsLocked()) {
            return false;
        }
        //检查customer
        CusCustomer cusCustomer = customerService.findShortById(cusUser.getRefCustomerId());
        return !(cusCustomer == null || cusCustomer.getDeleted());
    }
}
